const ioc = require('socket.io-client');
const _ = require('lodash');

class Core {
  constructor() {
    this.evt = {};
    const {npm_config_token: token, npm_config_url} = process.env;

    const url = npm_config_url + '/?token=' + token;
    console.log('url', url);

    const socket = ioc(url, {reconnection: false});
    this.socket = socket;

    socket.on('connect_error', err => {
      console.error(err);
    });

    socket.on('disconnect', () => {
      console.error('断开连接');
      process.exit(0);
    });

    socket.on('connect', () => {
      console.log('成功连接到 控制端');
      if (this.evt['ready'])
        this.evt['ready'].forEach(callback => callback());
    });

    socket.on('config', (data) => {
      this.config = data;
      if (this.evt['config'])
        this.evt['config'].forEach(callback => callback(data));
    });

    socket.on('task', (data) => {
      if (this.evt['task'])
        this.evt['task'].forEach(callback => callback(data));
    });
  }

  addEventListener(evtName, callback) {
    if (!this.evt[evtName])
      this.evt[evtName] = [];
    if (this.evt[evtName].indexOf(callback) === -1)
      this.evt[evtName].push(callback);
  }

  removeEventListener(evtName, callback) {
    if (this.evt[evtName]) {
      const evt = this.evt[evtName];
      const index = evt.indexOf(callback);
      if (index !== -1) {
        evt.splice(index, 1);
      }
    }
  }

  emit(name, data) {
    this.socket.emit(name, data);
  }

  emitError(error) {
    if (error instanceof Error)
      this.socket.emit('vps_error', error.message + '\n' + error.stack);
    else if (error.constructor === String)
      this.socket.emit('vps_error', error);
  }
}

module.exports = Core;